//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using Eas.WebCrawler.Model.Core;
using Eas.WebCrawler.Interfaces;

namespace Eas.WebCrawler.Model.Actions {
    internal class GetRequestAction : SleepingAction {
        #region ProcessingAction Members

        public override ProcessingAction EndAction(WorkerContext context, Eas.WebCrawler.Model.Core.BaseProcessingState state, IAsyncResult result) {
            base.EndAction(context, state, result);

            context.EventReporter.ReportTrace(TraceLevel.Annoying, state, "Getting next request from store");
            Eas.WebCrawler.Interfaces.Request nextRequest = context.WebCrawlerContext.Store.PopRequest();

            if (nextRequest != null) {
                context.EventReporter.ReportTrace(TraceLevel.Detailed, state, "Found request: {0}", nextRequest.Uri);
                state.Request = nextRequest;
                context.EventReporter.ReportWebRequestStarted(state);
                return context.ActionFactory.CreateGetResponseAction(state, context);
            }
            else {
                context.EventReporter.ReportTrace(TraceLevel.Detailed, state, "No requests, returning PendingGetRequestAction.");
                return context.ActionFactory.CreatePendingGetRequestAction(state, context);
            }
            
            /*if (context.StateTracker.GetCountOfWorkersInAction(ActionId.PendingGetRequest) + context.StateTracker.GetCountOfWorkersInAction(ActionId.Terminal) == context.WebCrawlerContext.WorkerCount) {
                context.EventReporter.ReportTrace(TraceLevel.Detailed, state, "No requests, and there are no pending workers, terminating.");
                return context.ActionFactory.CreateTerminalAction(state, context);
            }
            else {
                context.EventReporter.ReportTrace(TraceLevel.Detailed, state, "No requests but there are still pending workers, waiting.");
                return this;
            }*/
        }

        public override Eas.WebCrawler.Interfaces.WorkerState WorkerState {
            get { return Eas.WebCrawler.Interfaces.WorkerState.Working; }
        }

        public override ActionId ActionId {
            get {return ActionId.GetRequest;}
        }

        #endregion
    }   
}
